package Reports;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
	static Connection conn = null;

	public Test() {
		initSql();
	}

	public static void initSql() {
		final String driverClass = "oracle.jdbc.driver.OracleDriver";
		final String connectionString = "jdbc:oracle:thin:@localhost:1521:XE";
		final String userName = "miao";
		final String passwd = "miao";

		if (conn == null)
			try {
				conn = DBConnecter.getConnection(driverClass, connectionString,
						userName, passwd);
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}

	public String getMoto(String motorecycletype, String item_id) {
		PreparedStatement pstat = null;
		String temp = "\\w*\\+\\w*";
		String reg ="";
		try {
			String sql = "SELECT TYPENAME FROM  CHYIII_DEC_TMOTORCYCLETYPE";
			pstat = conn.prepareStatement(sql);
			ResultSet rs = pstat.executeQuery();
			while (rs.next()) {
				reg = rs.getString("TYPENAME");
			    temp =temp+ "|"+reg;
			}
		System.out.println(temp);
			Pattern pattern = Pattern.compile(temp);
			Matcher m = pattern.matcher(item_id);
			if (m.find()) {
				String mototype = m.group();
				System.out.println("mototype=="+mototype);
				return mototype;
			}

		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			try {
				if (pstat != null)
					pstat.close();
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return motorecycletype;
	}

	public String getMotorecycleType(String motorecycletype, String item_id)
			throws SQLException {
		String sql = "select * from CHYIII_DEC_TMOTORCYCLETYPE where typename='"
				+ motorecycletype + "'";
		PreparedStatement pstat = null;
		try {
			pstat = conn.prepareStatement(sql);
			ResultSet rs = pstat.executeQuery();
			if (!rs.next()) {
				return getMoto(motorecycletype, item_id);
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			try {
				if (pstat != null)
					pstat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return motorecycletype;
	}

	public static void main(String[] args) throws SQLException {
		String item_id = "EC-B 21-2013-0134-GS-JG-01_1";
		String type = "J11";
		Test t = new Test();
		String finalname = t.getMotorecycleType(type, item_id);
		System.out.println(finalname);

	}
}
